import { Injectable } from '@nestjs/common';

import * as OSS from 'ali-oss';

const ossConfig = {
  region: 'oss-cn-heyuan',
  bucket: 'xf-bucket',
  accessKeyId: 'LTAI5tGamY2EwAqUHtm3uv4i',
  accessKeySecret: 'zAqowrNfKgfnzUracAhEgjOkGY9GMx',
};

@Injectable()
export class OssService {
  private client: OSS;

  constructor() {
    this.client = new OSS({
      region: ossConfig.region,
      bucket: ossConfig.bucket,
      accessKeyId: ossConfig.accessKeyId,
      accessKeySecret: ossConfig.accessKeySecret,
    });
  }

  // 获取签名
  async signature() {
    const date = new Date();
    date.setDate(date.getDate() + 1);

    const res = this.client.calculatePostSignature({
      expiration: date.toISOString(),
      conditions: [['content-length-range', 0, 1048576000]],
    });
    const location = await this.client.getBucketLocation(ossConfig.bucket);
    const host = `https://${ossConfig.bucket}.${location.location}.aliyuncs.com`;
    return {
      ...res,
      host,
    };
  }

  // 上传文件
  // async put(ossPath: string, localPath: string) {
  //   let res: OSS.PutObjectResult;
  //   try {
  //     res = await this.client.put(ossPath, localPath);
  //     await this.client.putACL(ossPath, 'public-read');
  //   } catch (error) {
  //     console.log(error);
  //   }
  //   return res.url;
  // }

  //
}
